import React, { useState, useEffect } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Space,
  Modal,
  TreeSelect,
  InputNumber,
  message,
  Tag,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import Icon from "@/component/common/Icon";
import { $get, $post } from "@/api/RestUtils";
import TimeUtils from "@/utils/TimeUtils";
import TreeUtils from "@/utils/TreeUtils";
import "./index.less";
import { useSelector } from "react-redux";

const App: React.FC = () => {
  const permissionList: string[] = useSelector(
    (state: any) => state.permissions
  );

  const [searchForm] = Form.useForm();
  const [dataForm] = Form.useForm();

  const [infoModalShow, setInfoModalShow] = useState(false);
  const [infoModalTitle, setInfoModalTitle] = useState("");

  const [sourceList, setSourceList] = useState<any[]>();
  const [modalSourceList, setModalSourceList] = useState<any[]>();

  const [sourceType, setSourceType] = useState<number>();

  const availableList = [
    {
      available: 0,
      availableName: "锁定",
    },
    {
      available: 1,
      availableName: "正常",
    },
  ];

  const sourceTypes = [
    {
      type: 0,
      typeName: "目录",
    },
    {
      type: 1,
      typeName: "菜单",
    },
    {
      type: 2,
      typeName: "按钮",
    },
  ];

  let field = {
    id: "sourceId",
    parentId: "parentId",
  };

  const rootNode = {
    key: 0,
    sourceId: 0,
    sourceName: "主类目",
    sort: 0,
    sourceType: 0,
  };

  const columns: ColumnsType<SourceDataType> = [
    {
      title: "资源名称",
      dataIndex: "sourceName",
      key: "sourceName",
      width: 150,
      align: "center",
    },
    {
      title: "图标",
      dataIndex: "icon",
      key: "icon",
      width: 160,
      align: "center",
      render: (icon: string) => {
        return icon ? <Icon icon={icon} /> : "-";
      },
    },
    {
      title: "权限标识",
      dataIndex: "sourceCode",
      key: "sourceCode",
      width: 240,
      align: "center",
    },
    {
      title: "组件路径",
      dataIndex: "sourceRoute",
      key: "sourceRoute",
      width: 200,
      align: "center",
      render: (sourceRoute: string) => {
        return sourceRoute ? sourceRoute : "-";
      },
    },
    {
      title: "排序",
      dataIndex: "sort",
      key: "sort",
      width: 100,
      align: "center",
      render: (sort: number) => {
        return sort ? sort : "-";
      },
    },
    // {
    //   title: "状态",
    //   key: "action",
    //   width: 100,
    //   align: "center",
    //   render: (record: any) => {
    //     return <Switch checked={record.available === 1} onClick={(checked, event) => changeAvailable(checked, record.sourceId)} />;
    //   },
    // },
    {
      title: "类型",
      key: "action",
      width: 100,
      align: "center",
      render: (record: any) => {
        if (record.sourceType === 0) {
          return <Tag color="orange">目录</Tag>;
        } else if (record.sourceType === 1) {
          return <Tag color="blue">菜单</Tag>;
        } else {
          return <Tag color="green">按钮</Tag>;
        }
      },
    },
    {
      title: "创建时间",
      dataIndex: "ctime",
      key: "ctime",
      width: 240,
      align: "center",
      render: (ctime: Date) => {
        return TimeUtils.format(ctime);
      },
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      align: "center",
      width: 400,
      render: (record: any) => {
        return (
          <Space size="middle">
            <Button
              type="link"
              icon={<Icon icon="EditOutlined" />}
              size="small"
              onClick={() => switchDataModalShow(true, 1, record)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.source:update")
              }
            >
              修改
            </Button>
            <Button
              type="link"
              icon={<Icon icon="DeleteOutlined" />}
              size="small"
              onClick={() => deleteSourceConfirm(record.sourceId)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.source:delete")
              }
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    search();
  }, []);

  const switchDataModalShow = (show: boolean, model: number, formData: any) => {
    setInfoModalShow(show);
    if (model === 0) {
      // 新增
      setInfoModalTitle("新增角色信息");
    } else {
      // 修改
      setInfoModalTitle("修改角色信息");
      dataForm.setFieldsValue(formData);
      setSourceType(formData.sourceType);
    }
  };

  const dataFormValueChange = (changedValues: any) => {
    if (changedValues["sourceType"] != null) {
      setSourceType(changedValues["sourceType"]);
    }
  };

  const closeModal = () => {
    setInfoModalShow(false);
    resetDataForm();
  };

  const saveOrUpdate = (formData: any) => {
    let url;
    if (formData.sourceId != null) {
      url = "/source/update";
    } else {
      url = "/source/save";
    }
    $post(url, formData)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          search();
          closeModal();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  // const changeAvailable = (checked: boolean, sourceId: number) => {
  //   let available = checked ? 1 : 0;
  //   let param = {
  //     sourceId: sourceId,
  //     available: available
  //   }
  //   $post("/source/update", param).then((res: any) => {
  //     if (res.code === 0) {
  //       message.success(res.msg)
  //       search()
  //     } else {
  //       message.error(res.msg);
  //     }
  //   }).catch((err: any) => {
  //     message.error("系统异常")
  //   })
  // }

  const deleteSourceConfirm = (sourceId: number) => {
    Modal.confirm({
      title: "是否删除当前资源？",
      icon: <Icon icon="ExclamationCircleFilled" />,
      okText: "是",
      cancelText: "否",
      onOk() {
        deleteSource(sourceId);
      },
    });
  };

  const deleteSource = (sourceId: number) => {
    let param = {
      sourceId: sourceId,
    };
    $get("/source/delete", param)
      .then((res: any) => {
        if (res.code === 0) {
          message.success(res.msg);
          search();
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const renderAvailable = () => {
    let options = availableList.map((option: any) => {
      return { label: option.availableName, value: option.available };
    });
    return <Select options={options} placeholder="资源状态" />;
  };

  const renderSourceType = () => {
    let options = sourceTypes.map((option) => {
      return { label: option.typeName, value: option.type };
    });
    return <Select options={options} placeholder="类型" />;
  };

  const search = () => {
    $get("/source/find", searchForm.getFieldsValue())
      .then((res: any) => {
        if (res.code === 0) {
          let sourceList = TreeUtils.list2Tree(res.data, field);
          setSourceList(sourceList);
          res.data.push(rootNode);
          let modalSourceList = TreeUtils.list2Tree(res.data, field);
          setModalSourceList(modalSourceList);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const resetDataForm = () => {
    dataForm.resetFields();
  };

  const resetSearchForm = () => {
    searchForm.resetFields();
  };

  return (
    <>
      <Modal
        title={infoModalTitle}
        open={infoModalShow}
        closable={true}
        onCancel={closeModal}
        footer={null}
        className="source-save-modal"
      >
        <Form
          form={dataForm}
          labelAlign="right"
          layout="vertical"
          colon={false}
          onFinish={saveOrUpdate}
          onValuesChange={dataFormValueChange}
        >
          <Form.Item name="sourceId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="sourceName"
            label="资源名称"
            rules={[
              { required: true, type: "string", message: "请输入资源名称" },
              { max: 12, min: 2, message: "长度在2~12位之间" },
            ]}
          >
            <Input placeholder="资源名称" maxLength={12} />
          </Form.Item>
          <Form.Item
            name="sourceCode"
            label="资源标识"
            rules={[
              { required: true, type: "string", message: "请输入资源标识" },
              { max: 24, min: 2, message: "长度在2~24位之间" },
            ]}
          >
            <Input placeholder="资源标识" maxLength={24} />
          </Form.Item>

          <Form.Item
            name="sourceType"
            label="类型"
            rules={[{ required: true, message: "请选择资源类型" }]}
          >
            {renderSourceType()}
          </Form.Item>
          {sourceType != null && [1].includes(sourceType) ? (
            <Form.Item name="sourceRoute" label="组件路由">
              <Input placeholder="组件路由" maxLength={24} />
            </Form.Item>
          ) : (
            <></>
          )}
          {sourceType != null && [0, 1].includes(sourceType) ? (
            <Form.Item
              name="icon"
              label="图标"
              tooltip="可访问 https://ant.design/components/icon-cn， 获取图标库。只录入图标名称即可，如使用<StepBackwardOutlined />，录入StepBackwardOutlined即可"
            >
              <Input placeholder="图标" maxLength={32} />
            </Form.Item>
          ) : (
            <></>
          )}

          {sourceType != null && [0, 1].includes(sourceType) ? (
            <Form.Item
              name="sort"
              label="排序值"
              rules={[
                { required: true, type: "number", message: "请输入排序值" },
                {
                  max: 99,
                  min: 0,
                  type: "number",
                  message: "数值在0~99位之间",
                },
              ]}
            >
              <InputNumber placeholder="排序值" maxLength={3} />
            </Form.Item>
          ) : (
            <></>
          )}
          <Form.Item
            name="parentId"
            label="父资源"
            rules={[{ required: true, message: "请输入选择父资源" }]}
          >
            <TreeSelect
              showSearch
              style={{ width: "100%" }}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
              placeholder="请选择父资源"
              allowClear
              treeData={modalSourceList}
              fieldNames={{
                label: "sourceName",
                value: "sourceId",
                children: "children",
              }}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={resetDataForm}>重置</Button>
          </Form.Item>
        </Form>
      </Modal>
      <div className="source-body">
        <div className="search-condition">
          <Form
            form={searchForm}
            labelAlign="left"
            name="horizontal_login"
            colon={false}
          >
            <div className="form-body">
              <Form.Item name="sourceName" label="资源名称">
                <Input placeholder="资源名称" maxLength={12} />
              </Form.Item>
              <Form.Item name="available" label="状态">
                {renderAvailable()}
              </Form.Item>
            </div>
            <div className="form-footer">
              <Form.Item>
                <Button
                  type="primary"
                  icon={<Icon icon="SearchOutlined" />}
                  onClick={() => search()}
                >
                  查询
                </Button>
                <Button
                  icon={<Icon icon="ReloadOutlined" />}
                  onClick={resetSearchForm}
                >
                  重置
                </Button>
              </Form.Item>
            </div>
          </Form>
        </div>
        <div className="table-area">
          <div className="operate-btn-group">
            <Button
              type="dashed"
              icon={<Icon icon="PlusOutlined" />}
              onClick={() => switchDataModalShow(true, 0, null)}
              disabled={
                !permissionList ||
                !permissionList.includes("system.source:save")
              }
            >
              新增
            </Button>
          </div>
          <div className="table-data">
            <Table
              pagination={false}
              dataSource={sourceList}
              columns={columns}
              scroll={{ x: 1200 }}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default App;
